/*******************************************************************************
 * 版权：北京润尼尔网络科技有限公司，保留所有版权<br>
 * 版本：v1.0.0<br>
 * 文件：CommandAddParaImg.js<br>
 * 日期：2018年11月21日<br>
 * 作者: 李姣<br>
 * 功能：发散流程框添加横向图片命令<br>
 * 
 * 修改记录：<br>
 * 日期 描述 更新功能<br>
 ******************************************************************************/

window.makeNamespace(window,"Rainier.UI.V2");

/**
 * 类型名称：Rainier.UI.V2.CommandAddParaImg<br>
 * 类型功能：发散流程框添加图片命令<br>
 */
Rainier.UI.V2.CommandAddParaImg = draw2d.command.Command.extend({
	
	NAME : "Rainier.UI.V2.CommandAddParaImg",
	
	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.init<br>
	 * 函数功能：构造函数<br>
	 * 异常信息：无<br>
	 */
	init : function(context,editParts){
		this.context 		= context;
		this.editPart       = editParts.data[0];
		this.addInfo = {};
		this.deleteInfo = {};
		this.tabId = app.canvasId;
    		this.rootEditPart 	= this.context.getRootEditPart();
    		this.activeEditor = app.getContext().getActiveEditor();
    		this.distanceY = 80;
		this.distanceX = 180;
		this._super();
	},
	
    /**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.execute<br>
	 * 函数功能：执行命令<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
    execute:function(){
    	var _this = this;
    	var json = Rainier.UI.V2.Communication.CustomImgPara;
    	var createdModel = this.deleteInfo.model;
		if(createdModel){
			var portList 	= this.deleteInfo.ports.clone();
			portList.each(function(index,port){
				createdModel.addPort(port);
			});
		}
		else{
			createdModel = Rainier.UI.V2.DeviceModelBuilder.buildModel(json);
		}
		//添加器件id
		if(!createdModel.property.modelProperty.id){
			createdModel.property.modelProperty.id = (new Date()).getTime();
		}
		var model = this.editPart.getModel();
		//选中器件的位置和属性
		var property = model.property;
		var modelProperty = property.modelProperty;
		var uiProperty = property.uiProperty;
		var parentX = uiProperty.x;
		var parentY = uiProperty.y;
		
		var newChildX = null;
		var newChildY = null;
		var childNum = modelProperty.children.length;
		var parentModel = this.editPart.getParent().getModel();

		var leftChildren = [];
		var rightChildren = [];
		if(childNum>0){
			//分开左右子节点
			$.each(modelProperty.children,function(index,child){
				var childModel = _this.getModelById(child);
				if(childModel === null){
					childModel = _this._getModelById(child);
				}
				if(childModel.property.modelProperty.position=='left'){
					leftChildren.push(child);
				}
				else if(childModel.property.modelProperty.position=='right'){
					rightChildren.push(child);
				}
			});
		}

		// var newChildX = parentX+uiProperty.width+90;
		if(modelProperty.imgArr){
			if(modelProperty.imgArr.length>0){
				var id = modelProperty.imgArr[modelProperty.imgArr.length-1];
				var _model=_this.getModelById(id);
				if(!_model){
					_model = _this._getModelById(id);
				}
				if(_model){
					newChildX = _model.property.uiProperty.x+10;
				}
			}
		}
		else{
			alert("不能添加图片~");
			return;
		}
		//根节点
		if(!modelProperty.parent){
			//没有子节点
			if(childNum==0){
				//第一个子节点在根节点正右边
				createdModel.property.modelProperty.position = 'right';
				newChildX = parentX+uiProperty.width+this.distanceX;
				newChildY = parentY + uiProperty.height/2-createdModel.property.uiProperty.height/2;
				//添加新孩子
				parentModel.addChildModel(createdModel);
				createdModel.setPosition(newChildX,newChildY,false);
			}
			//有子节点
			else{
				//已有奇数个子节点
				if(childNum%2!=0){
					//新节点添加在左边
					createdModel.property.modelProperty.position = 'left';
					//左边没有子节点
					if(leftChildren.length==0){
						//新节点在正左边
						newChildX = parentX-createdModel.property.uiProperty.width-this.distanceX;
						newChildY = parentY + uiProperty.height/2-createdModel.property.uiProperty.height/2;
						//添加新孩子
						parentModel.addChildModel(createdModel);
						createdModel.setPosition(newChildX,newChildY,false);
					}
					//左边有子节点
					else{
						//新节点下移
						var searchedOddModel = this.getModelById(leftChildren[leftChildren.length-1]);
						if(searchedOddModel === null){
							searchedOddModel = this._getModelById(leftChildren[leftChildren.length-1]);
						}
						newChildX = searchedOddModel.property.uiProperty.x;
						newChildY = searchedOddModel.property.uiProperty.y+this.distanceY;
						//左边子节点上移
						this.moveUpTree(model,'up',this.distanceY);
						this.moveDownTree(model,'down',this.distanceY);
						this.moveChildren(leftChildren,'up',this.distanceY);
						//上面树结构上移，下面树结构下移
						
						//添加新孩子
						parentModel.addChildModel(createdModel);
						createdModel.setPosition(newChildX,newChildY,false);
					}
				}
				//偶数个子节点
				else{
					//新节点在右边
					createdModel.property.modelProperty.position = 'right';
					//新节点下移
					var searchedEvenModel = this.getModelById(rightChildren[rightChildren.length-1]);
					if(searchedEvenModel === null){
						searchedEvenModel = this._getModelById(rightChildren[rightChildren.length-1]);
					}
					newChildX = searchedEvenModel.property.uiProperty.x;
					newChildY = searchedEvenModel.property.uiProperty.y+this.distanceY;
					//0除外，右边一定有子节点，子节点上移
					this.moveUpTree(model,'up',this.distanceY);
					this.moveDownTree(model,'down',this.distanceY);
					this.moveChildren(rightChildren,'up',this.distanceY);
					//添加新孩子
					parentModel.addChildModel(createdModel);
					createdModel.setPosition(newChildX,newChildY,false);
				}
			}
		}
		//非根节点
		else{
			//在根节点左边
			if(modelProperty.position=='left'){
				createdModel.property.modelProperty.position = 'left';
				//没有子节点
				if(childNum==0){
					//新节点在正左边
					newChildX = parentX-createdModel.property.uiProperty.width-this.distanceX;
					newChildY = parentY + uiProperty.height/2-createdModel.property.uiProperty.height/2;
					//添加新孩子
					parentModel.addChildModel(createdModel);
					createdModel.setPosition(newChildX,newChildY,false);
				}
				//有子节点,子节点上移
				else{
					//新节点下移
					var children = modelProperty.children;
					var searchedLeftModel = this.getModelById(children[children.length-1]);
					if(searchedLeftModel === null){
						searchedLeftModel = this._getModelById(children[children.length-1]);
					}
					newChildX = searchedLeftModel.property.uiProperty.x;
					newChildY = searchedLeftModel.property.uiProperty.y+this.distanceY;
					newChildX = this.getModelById(children[children.length-1]).property.uiProperty.x;
					newChildY = this.getModelById(children[children.length-1]).property.uiProperty.y+this.distanceY;
					this.moveUpTree(model,'up',this.distanceY);
					this.moveDownTree(model,'down',this.distanceY);
					this.moveChildren(children,'up',this.distanceY);
					//添加新孩子
					parentModel.addChildModel(createdModel);
					createdModel.setPosition(newChildX,newChildY,false);
				}
			}
			//在右边
			else if(modelProperty.position=='right'){
				createdModel.property.modelProperty.position = 'right';
				//没有子节点
				if(childNum==0){
					//新节点在正右边
					newChildX = parentX+uiProperty.width+this.distanceX;
					newChildY = parentY + uiProperty.height/2-createdModel.property.uiProperty.height/2;
					//添加新孩子
					parentModel.addChildModel(createdModel);
					createdModel.setPosition(newChildX,newChildY,false);
				}
				//有子节点
				else{
					//新节点下移
					var children = modelProperty.children;
					var searchedRightModel = this.getModelById(children[children.length-1]);
					if(searchedRightModel === null){
						searchedRightModel = this._getModelById(children[children.length-1]);
					}
					newChildX = searchedRightModel.property.uiProperty.x;
					newChildY = searchedRightModel.property.uiProperty.y+this.distanceY;
					//子节点上移
					this.moveUpTree(model,'up',this.distanceY);
					this.moveDownTree(model,'down',this.distanceY);
					this.moveChildren(children,'up',this.distanceY);
					//添加新孩子
					parentModel.addChildModel(createdModel);
					createdModel.setPosition(newChildX,newChildY,false);
				}
			}
		}
		//添加子节点信息
		modelProperty.children.push(createdModel.property.modelProperty.id);

		//连线
		var sPort = null,tPort=null;
		var parentPorts = this.getPorts(model);
		var childPorts = this.getPorts(createdModel);
		var connection = Rainier.UI.V2.Communication.ConnectionModel[0];
		connection.uuid = (new Date()).getTime();
		connection.modelProperty.direction = "horizontal";
		var segment = connection.modelProperty.segments;

		if(createdModel.property.modelProperty.position == 'left'){
			$.each(parentPorts,function(index,port){
				if(port.property.modelProperty.locator.x==0){
					sPort = port;
				}
			});
			$.each(childPorts,function(index,port){
				if(port.property.modelProperty.locator.x==createdModel.property.uiProperty.width){
					tPort = port;
				}
			});
			segment[1].start_x = parentX;
			segment[1].start_y = createdModel.property.uiProperty.y+createdModel.property.uiProperty.height/2;
		}
		else{
			$.each(parentPorts,function(index,port){
				if(port.property.modelProperty.locator.x==uiProperty.width){
					sPort = port;
				}
			});
			$.each(childPorts,function(index,port){
				if(port.property.modelProperty.locator.x==0){
					tPort = port;
				}
			});
			segment[1].start_x = parentX+uiProperty.width;
			segment[1].start_y = createdModel.property.uiProperty.y+createdModel.property.uiProperty.height/2;
		}
		this.activeEditor.makeConnection(sPort,tPort,connection);

		//判断器材展示栏中是否已存在该器材，若存在则不再再次向展示栏中添加
		var className = createdModel.property.modelProperty.typeName;
		var componentName = createdModel.property.modelProperty.componentName;
		this.addUsedPart(className,componentName);

		// this.refreshConnection();
		this.addInfo.createdModel = createdModel;

		//存储图片
		modelProperty.imgArr.push(createdModel.m_sUuid);
		//更新预览图
		// if(isSelectedPreview){
		// 	setTimeout(function(){
		// 		var img = $("#img-preview");
		// 		refreshPreview(img);
		// 	});
		// }
    },
    
	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.undo<br>
	 * 函数功能：撤销命令<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	undo:function(){
		var model = this.addInfo.createdModel;
		var modelProperty = this.editPart.getModel().property.modelProperty;
		var parentModel = this.editPart.getParent().getModel();
		// 删除已添加到已使用器材的器件
		var className = model.property.modelProperty.typeName;
		if(className !== "OverThreeTextModelJson"){
			// 删除已使用器材
			this.deleteUsedPart(className);
		}

		this.deleteInfo=parentModel.removeChildModel(model);
		//父节点删除子信息
		var parentId = model.property.modelProperty.parent;
		var parent =  this.getModelById(parentId);
		if(parent){
			var children = parent.property.modelProperty.children;
    			var _children = [];
			for(var i=0;i<children.length;i++){
				var _id = children[i];
				if(_id==id){
					var index = children.indexOf(_id);
					children.splice(index,1);
				}
				else{
					_children.push(_id);
				}
			}
			var position = model.property.modelProperty.position;
			var childArr = [];
			$.each(_children,function(index,child){
				var childModel = _this.getModelById(child);
				if(childModel.property.modelProperty.position == position){
					childArr.push(child);
				}
			});
			//老孩子移动到原位
			
    			this.moveChildren(childArr,'down',this.distanceY);
			if(children.length>0){
				this.moveUpTree(parent,'down',this.distanceY);
				this.moveDownTree(parent,'up',this.distanceY);
			}
			if(modelProperty.imgArr){
				var index = modelProperty.imgArr.indexOf(model.m_sUuid);
				modelProperty.imgArr.splice(index,1);
			}
		}
		// this.refreshConnection();
	},
    
	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.redo<br>
	 * 函数功能：重做命令<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	redo:function(){
		this.execute();
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.getPorts<br>
	 * 函数功能：获取端口<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	getPorts : function(model){
		var ports = [];
		var inputs   = model.getInputPorts();
		var outputs  = model.getOutputPorts();
		var hybrids  = model.getHybridPorts();
		
		inputs.each(function(i,p){
			ports.push(p);
		});
		outputs.each(function(i,p){
			ports.push(p);
		});
		hybrids.each(function(i,p){
			ports.push(p);
		});
		return ports;
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.moveUpTree<br>
	 * 函数功能：上子树上移,避免重合<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	moveUpTree : function(model,direction,distance){
		var _this = this;
		var parent = model.property.modelProperty.parent;
		//model是根节点
		if(!parent){
			return;
		}
		var parentModel = this.getModelById(parent);
		var children = parentModel.property.modelProperty.children;
		var modelId = model.property.modelProperty.id;
		//父节点不是根节点
		if(parentModel.property.modelProperty.parent){
			var index = children.indexOf(modelId);
			var childrenUp = children.slice(0,index);
			this.moveChildren(childrenUp,direction,distance);
			this.moveUpTree(parentModel,direction,distance);
		}
		//model的父节点是根节点
		else{
			//会包含另一边的子节点
			var position = model.property.modelProperty.position;
			var leftChildren = [];
			var rightChildren = [];
			//分开左右子节点
			$.each(children,function(index,child){
				var childModel = _this.getModelById(child);
				if(childModel === null){
					childModel = _this._getModelById(child);
				}
				if(childModel.property.modelProperty.position=='left'){
					leftChildren.push(child);
				}
				else if(childModel.property.modelProperty.position=='right'){
					rightChildren.push(child);
				}
			});
			if(position=='left'){
				var index = leftChildren.indexOf(modelId);
				var childrenUp = leftChildren.slice(0,index);
				this.moveChildren(childrenUp,direction,distance);
			}
			else if(position=='right'){
				var index = rightChildren.indexOf(modelId);
				var childrenUp = rightChildren.slice(0,index);
				this.moveChildren(childrenUp,direction,distance);
			}
		}
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.moveDownTree<br>
	 * 函数功能：下子树下移<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	moveDownTree : function(model,direction,distance){
		var _this = this;
		var parent = model.property.modelProperty.parent;
		//model是根节点
		if(!parent){
			return;
		}
		var parentModel = this.getModelById(parent);
		var children = parentModel.property.modelProperty.children;
		var modelId = model.property.modelProperty.id;
		//父节点不是根节点
		if(parentModel.property.modelProperty.parent){
			var index = children.indexOf(modelId);
			var childrenDown = children.slice(index+1);
			this.moveChildren(childrenDown,direction,distance);
			this.moveDownTree(parentModel,direction,distance);
		}
		//model的父节点是根节点
		else{
			//会包含另一边的子节点
			var position = model.property.modelProperty.position;
			var leftChildren = [];
			var rightChildren = [];
			//分开左右子节点
			$.each(children,function(index,child){
				var childModel = _this.getModelById(child);
				if(childModel === null){
					childModel = _this._getModelById(child);
				}
				if(childModel.property.modelProperty.position=='left'){
					leftChildren.push(child);
				}
				else if(childModel.property.modelProperty.position=='right'){
					rightChildren.push(child);
				}
			});
			if(position=='left'){
				var index = leftChildren.indexOf(modelId);
				var childrenDown = leftChildren.slice(index+1);
				this.moveChildren(childrenDown,direction,distance);
			}
			else if(position=='right'){
				var index = rightChildren.indexOf(modelId);
				var childrenDown = rightChildren.slice(index+1);
				this.moveChildren(childrenDown,direction,distance);
			}
		}
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.moveChildren<br>
	 * 函数功能：上下移动子节点<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	moveChildren : function(children,direction,distance){
		var _this = this;
		for(var i=0;i<children.length;i++){
			var _id = children[i];
			var childModel = this.getModelById(_id);
			if(childModel === null){
				childModel = this._getModelById(_id);	
			}
			var uiProperty = childModel.property.uiProperty;
			var x = uiProperty.x;
			var y = uiProperty.y;
			var oldChildY = null;
			if(direction=='up'){
				oldChildY = y - distance;
			}
			if(direction=='down'){
				oldChildY = y + distance;
			}
			var oldChildX = x;
			//更新老孩子位置
			childModel.setPosition(oldChildX,oldChildY,false);
			var _children = childModel.property.modelProperty.children;
			if(_children){
				if(direction=='up'){
					_this.moveChildren(_children,'up',distance);
				}
				if(direction=='down'){
					_this.moveChildren(_children,'down',distance);
				}
			}
		}
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.refreshConnection<br>
	 * 函数功能：重新绘制连线<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	refreshConnection : function(){
		//删除错误连线
		//遍历三次，否则不能删除干净
		var connections = this.activeEditor.rootModel.connections.data;
		var _connection = Rainier.UI.V2.Communication.ConnectionModel[0];
			
		for(var j=0;j<3;j++){
			connections = this.activeEditor.rootModel.connections.data;
			for(var i=0;i<connections.length;i++){
				var connection = connections[i];
				// 只刷新竖向连线
				if(connection.property.modelProperty.direction !== "undefined" && connection.property.modelProperty.direction== "horizontal"){
					var segments = connection.property.modelProperty.segments;
					if(segments.length>1){
						if(segments[0].type=="horizontal"||segments[1].type=="vertical"){
							//确保新线完成再删除错误
							var complete = false;
							//确保id相同
							_connection.uuid = connection.m_sUuid;
							//删除连线
							var sourcePort = connection.sourcePort;
							var targetPort = connection.targetPort;
							var _segment = connection.property.modelProperty.segments;
							var x = _segment[0].start_x;
							var y = _segment[1].end_y;
							if(sourcePort){
								var segment = _connection.modelProperty.segments;
								segment[1].start_x = x;
								segment[1].start_y = y;
								this.activeEditor.makeConnection(sourcePort,targetPort,_connection);
							}
							complete = true;
							if(complete){
								this.rootEditPart.getModel().removeConnection(connection);
							}
						}
					}
				}
			}
		}
	},

      /**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.getModelById<br>
	 * 函数功能：根据主题id查询对应model<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	getModelById : function(id){
		var parentModel = this.editPart.getParent().getModel();
		var children = parentModel.m_aChildren;
		var model = null;
		if(children){
			$.each(children,function(index,child){
				var _id = child.property.modelProperty.id;
				if(_id==id){
					model = child;
				}
			});
		}
		return model;
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg._getModelById<br>
	 * 函数功能：根据主题id在已经隐藏图片库查询对应model<br>
	 * 参数输入：无<br>
	 * 参数输出：无<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	_getModelById : function(id){
		var model = null;
		var hideArr = hideImgArr[this.tabId];
		if(hideArr){
			if(hideArr.length>0){
				$.each(hideArr,function(index,deleteInfo){
					var _id = deleteInfo.model.property.modelProperty.id;
					if(_id==id){
						model = deleteInfo.model;
					}
				});
			}
		}
		return model;
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.addUsedPart<br>
	 * 函数功能：(单个添加器件)判断器材展示栏中是否已存在该器材，若存在则不再再次向展示栏中添加<br>
	 * 函数输入：className和componentName
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	addUsedPart : function(className,componentName){
		// if(className === "OverThreeTextModelJson" || className === "TextModelJson2" || className === "TextModelJson3"){
		// 	className = "TextModelJson";
		// }
		var usedPart = {};
		usedPart.isLogic = true;
		usedPart.courseType = "Communication";
		usedPart.deviceType = "PmsModel";
		//data_part:data的一个对象
		var data_part = {};
		data_part.className = className;
		// 还未向实验台添加器件时
		if(data.length == 0){
			if(className){
				data_part.addCount = 1;
			}
			data.push(data_part);
			usedPart.className = data[0].className;
			usedPart.componentName = componentName;
			usedPartArray.push(usedPart);
			// console.log(data);
			// console.log(usedPartArray);
		// 实验台上已经存在器件时
		}else{
			for(var i=0;i<data.length;i++){
				if(data[i].className == className){
					// console.log("已加入已使用器件数组!");
					data[i].addCount += 1;
					// console.log(data);
					return;
				}
			}
			data_part.addCount = 1;
			data.push(data_part);
			usedPart.className = data[data.length-1].className;
			usedPart.componentName = componentName;
			usedPartArray.push(usedPart);
			// console.log(data);
			// console.log(usedPartArray);
		}
		// console.log(data);
		// console.log(usedPartArray);
	},

	/**
	 * 函数名称：Rainier.UI.V2.CommandAddParaImg.deleteUsedPart<br>
	 * 函数功能：根据addCount的值删除器件展示栏中的器件，若为0，则删除<br>
	 * 函数返回：无<br>
	 * 异常信息：无<br>
	 */
	deleteUsedPart : function(className){
		if(className){
			for(var i=0;i<data.length;i++){
				if(className == data[i].className){
					data[i].addCount -=1;
					if(data[i].addCount > 0){
						// console.log(data);
						// console.log(usedPartArray);
						// console.log("实验台上还存在"+className);
						return;
					}else{
						data.splice(i, 1);
						// console.log(data);
						// addCount<=0且usedPartArray中存在该className对应的器件信息时，将该器件从器件展示栏删除
						for(var j=0;j<usedPartArray.length;j++){
							if(usedPartArray[j].className == className){
								usedPartArray.splice(j, 1);
								// console.log(usedPartArray);
							}
						}
					}
				}
			}
		}
	},
});